package response

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// APIResponse 定义统一的响应格式
type APIResponse struct {
	Code    int         `json:"code"`    // 状态码：200成功，400客户端错误，500服务器错误
	Message string      `json:"message"` // 响应消息
	Data    interface{} `json:"data"`    // 业务数据（可选）
}

// Success 返回成功响应
func Success(w http.ResponseWriter, data interface{}, message ...string) {
	msg := "操作成功"
	if len(message) > 0 {
		msg = message[0]
	}

	// 设置响应头
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	// 构建响应
	response := APIResponse{
		Code:    http.StatusOK,
		Message: msg,
		Data:    data,
	}

	// 序列化响应
	jsonData, err := json.Marshal(response)
	if err != nil {
		http.Error(w, fmt.Sprintf(`{"code":500,"message":"响应序列化失败: %v","data":null}`, err), http.StatusInternalServerError)
		return
	}

	// 发送响应
	w.WriteHeader(http.StatusOK)
	w.Write(jsonData)
}

// Error 返回错误响应
func Error(w http.ResponseWriter, code int, message string) {
	// 设置响应头
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	// 构建响应
	response := APIResponse{
		Code:    code,
		Message: message,
		Data:    nil,
	}

	// 序列化响应
	jsonData, err := json.Marshal(response)
	if err != nil {
		http.Error(w, fmt.Sprintf(`{"code":500,"message":"响应序列化失败: %v","data":null}`, err), http.StatusInternalServerError)
		return
	}

	// 发送响应
	w.WriteHeader(code)
	w.Write(jsonData)
}

// SSESuccess 发送SSE格式的成功响应
func SSESuccess(w http.ResponseWriter, data interface{}) {
	// 设置SSE响应头
	w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 构建响应
	response := APIResponse{
		Code:    http.StatusOK,
		Message: "操作成功",
		Data:    data,
	}

	// 序列化响应
	jsonData, err := json.Marshal(response)
	if err != nil {
		http.Error(w, fmt.Sprintf(`{"code":500,"message":"响应序列化失败: %v","data":null}`, err), http.StatusInternalServerError)
		return
	}

	// 发送SSE格式响应
	fmt.Fprintf(w, "data: %s\n\n", jsonData)

	// 刷新响应
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}
}

// SSEError 发送SSE格式的错误响应
func SSEError(w http.ResponseWriter, code int, message string) {
	// 设置SSE响应头
	w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("Access-Control-Allow-Origin", "*")

	// 构建响应
	response := APIResponse{
		Code:    code,
		Message: message,
		Data:    nil,
	}

	// 序列化响应
	jsonData, err := json.Marshal(response)
	if err != nil {
		http.Error(w, fmt.Sprintf(`{"code":500,"message":"响应序列化失败: %v","data":null}`, err), http.StatusInternalServerError)
		return
	}

	// 发送SSE格式响应
	fmt.Fprintf(w, "data: %s\n\n", jsonData)

	// 刷新响应
	if f, ok := w.(http.Flusher); ok {
		f.Flush()
	}
}
